#!/usr/bin/python
# --*-- coding: utf-8 --*--

# test_Weather.py

import json
import os
import time

import schedule as schedule
import xlwt

from Common.Send import send_requests


# 删除文件夹下面的所有文件(只删除文件,不删除文件夹)
# python删除文件的方法 os.remove(path)path指的是文件的绝对路径,如：

def del_file(path_data):
    for i in os.listdir(path_data):  # os.listdir(path_data)#返回一个列表，里面是当前目录下面的所有东西的相对路径
        file_data = path_data + "\\" + i  # 当前文件夹的下面的所有东西的绝对路径
        if os.path.isfile(file_data) == True:  # os.path.isfile判断是否为文件,如果是文件,就删除.如果是文件夹.递归给del_file.
            os.remove(file_data)
        else:
            del_file(file_data)


# 读取json中列表
path_data = r"../Export"
del_file(path_data)
file = open("../data/url_config.json", "r", encoding="utf-8")
# print(file)
url_config = json.load(file)
# print(url_config['pi-platform-auth'])
# 获取url_config下的pi-platform-auth中接口信息
url_list = url_config["pi-train-server"]
workbook = xlwt.Workbook(encoding="utf-8")  # 实例化book对象
sheet = workbook.add_sheet("xlwt方法")  # 生成sheet
login = url_config["pi-platform-auth"][0]
baseUrl = url_config["baseUrl"]


def my_func():
    try:
        response = send_requests(url=login["url"], method=login["method"], data=login["data"],
                                 headers={'Content-Type': 'application/json'})
        token = response.json()["data"]["token"]
        print(token)
        headers = {
            'Content-Type': 'application/json',
            "access_token": token
        }
        return headers
    except Exception as e:
        print(e, '=========================')
        return False


def my_save():
    headers = my_func()
    for col, column in enumerate(["名称", "请求类型", "Url地址", "Logging", "是否成功"]):
        sheet.write(0, col, column)
    row = 0
    for item in url_list:
        res = send_requests(url=baseUrl + item["url"], method=item["method"], data=item["data"],
                            headers=headers)
        row = row + 1
        print(res.json())
        for col, col_data in enumerate(item):
            if col == 3:
                sheet.write(row + 1, col, json.dumps(res.json()))
            elif col == 4:
                if res.json().get("code") == 0:

                    sheet.write(row + 1, col, True)
                else:
                    sheet.write(row + 1, col, False)
            else:
                sheet.write(row + 1, col, item[col_data])
    workbook.save("../export/接口用例详情.xls")


# 写入标题

if __name__ == '__main__':
    schedule.every().day.at("10:30").do(my_save())
    while True:
        # run_pending：运行所有可以运行的任务
        schedule.run_pending()
        time.sleep(1)

